import { ArticleCommentResponse, ArticleDetailResponse } from "@/types/data";
import { RootThunkAction } from "@/types/store";
import { http } from "@/utils/http";
import { useInitialState } from "@/utils/use-initial-state";
import dayjs from "dayjs";
import localizedFormat from "dayjs/plugin/localizedFormat";
import { useDispatch } from "react-redux";
import { useParams } from "react-router-dom";
dayjs.extend(localizedFormat);
// 详情页
export const getArticleById = async (id: string) => {
  const res = await http.get<ArticleDetailResponse>(`/articles/${id}`);

  const detail = res.data.data;
  return detail;
};
export const followAuthor = (
  id: string,
  isFollowed: boolean
): RootThunkAction => {
  return async (dispatch) => {
    if (isFollowed) {
      // 取关
      await http.delete(`/user/followings/${id}`);
    } else {
      // 关注
      await http.post(`/user/followings`, {
        target: id,
      });
    }
    dispatch({
      type: "article/updateInfo",
      payload: {
        name: "is_followed",
        value: !isFollowed,
      },
    });
  };
};
// 获取文章评论 - 覆盖数据
export const getArticleComment = async (type: string, id: string) => {
  const res = await http.get<ArticleCommentResponse>("/comments", {
    params: {
      type,
      source: id,
    },
  });
  
  return res;
};

// 获取更多文章评论数据 - 追加数据
export const getMoreArticleComments = (
  type: string,
  id: string,
  offset: string | null
): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<ArticleCommentResponse>("/comments", {
      params: {
        type,
        source: id,
        offset,
      },
    });
    console.log(res.data.data);
  };
};
// 收藏 or 取消收藏文章
export const collectArticle = (
  art_id: string,
  isCollected: boolean
): RootThunkAction => {
  return async (dispatch) => {
    // 判断当前是否收藏
    if (isCollected) {
      // 取消收藏
      http.delete(`/article/collections/${art_id}`);
    } else {
      // 收藏
      http.post("/article/collections", {
        target: art_id,
      });
    }

    dispatch({
      type: "article/updateInfo",
      payload: {
        name: "is_collected",
        value: !isCollected,
      },
    });
  };
};
// 点赞 or 取消点赞文章
export const likeArticle = (
  art_id: string,
  attitude: number
): RootThunkAction => {
  return async (dispatch) => {
    // 判断当前是否点赞
    // 如果是 1 表示已点赞
    if (attitude === 1) {
      // 取消点赞
      await http.delete(`/article/likings/${art_id}`);
    } else {
      // 点赞
      await http.post("/article/likings", {
        target: art_id,
      });
    }

    dispatch({
      type: "article/updateInfo",
      payload: {
        name: "attitude",
        value: attitude === 1 ? 0 : 1,
      },
    });
  };
};
